package cn.bookCity.servlet;

import java.util.HashMap;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.bookCity.domain.Products;
import cn.bookCity.service.ProductService;
import cn.bookCity.util.BeanFactory;

@WebServlet("/book/cart")
public class CartServlet extends BaseServlet{

	
	public String addCart(HttpServletRequest request,HttpServletResponse response)throws Exception{
		HttpSession session=request.getSession();
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		@SuppressWarnings("unchecked")
		HashMap<Products, Integer> cart=
    			(HashMap<Products, Integer>) session.getAttribute("cart");
		if(cart==null) {
			cart=new HashMap<>();
			session.setAttribute("cart", cart);
		}
		String[] ids=request.getParameterValues("bookId");
		if(ids!=null) {
			for(int i=0;i<ids.length;i++) {
				String id=ids[i];
				Products product=p.getProduct(id);
				Integer put=cart.put(product, 1);
				System.out.println(put);
				if(put!=null) {
					cart.put(product, put+1);
				}
			}
		}
		return "/shopping.jsp";
	}
	public String delCart(HttpServletRequest request,HttpServletResponse response)throws Exception {
		HttpSession session=request.getSession();
		@SuppressWarnings("unchecked")
		HashMap<Products, Integer> cart=(HashMap<Products, Integer>) session.getAttribute("cart");
		String id=request.getParameter("id");
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		Products product=p.getProduct(id);
		cart.remove(product);
		return "/shopping.jsp";
	}
	
	public String changeCart(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String id = request.getParameter("id");
		String count = request.getParameter("count");
		System.out.println("id=="+id);
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		HashMap<Products, Integer> cart=
    	   (HashMap<Products, Integer>) session.getAttribute("cart");
		ProductService ps=(ProductService)BeanFactory.getBean("ProductService");
		Products p = ps.getProduct(id);
		Integer num = Integer.parseInt(count);
		cart.put(p, num);
		return "/shopping.jsp";
	}
	
}
